package com.server.commons.security.Aspect;

import com.server.common.security.code.thread.ThreadLocalHeaderUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;

@Aspect
@Component
public class RabbitMQInterceptor {

    @Around("@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
    public Object around(ProceedingJoinPoint point) throws Throwable{

        Object[] args = point.getArgs();

        if(ObjectUtils.isEmpty(args)){
            return point.proceed();
        }

        for (Object obj:args){

            if(!(obj instanceof Message)){
                continue;
            }

            Message message = (Message) obj;

            Map<String, Object> headers = message.getMessageProperties().getHeaders();

            for (String key:headers.keySet()){

                if(!(headers.get(key) instanceof String)){
                    continue;
                }

                ThreadLocalHeaderUtils.addHeader(key, String.valueOf(headers.get(key)));
            }

            break;
        }

        return point.proceed();
    }
}
